/**
 * Created by Administrator on 2015/1/21.
 */
var express = require('express');
var service = require('./service');
var router = express.Router();
var logger = require('./logger');
var utils = require('./utils');
var Message = require('./message').Message;
var MongBase = require('./mongoBase');
var Fiber = require('fibers');

router.get('/map', function (req, res) {
    var query = req.query;
    var pass = service.verify(query);
    if (pass) {
        var echostr = query['echostr'];
        res.send(echostr);
    } else {
        res.send("bad token~");
    }
});

router.post('/map', function (req, res) {
    var xmlParam = req.body;
    var query = req.query;
    var pass = service.verify(query);
    if (!pass) {
        logger.info(Message.ILLEGAL_REQUEST);
        res.send(Message.ILLEGAL_REQUEST);
        return;
    }
    Fiber(function () {
        logger.debug("req body", xmlParam);
        var result = service.process(xmlParam);
        logger.info("view result", result);
        res.send(result);
    }).run();
});

router.get('/', function (req, res) {
    res.render('test');
});
router.get('/test', function (req, res) {
    logger.debug("req accepts", req.accepts('application/json'));
    var command = req.param("command");
    command = command.replace("$", "%");
    var from = req.param("from");
    logger.debug("command", command)
    var xmlParam = utils.processEjsTemplate("testContent", {command: command, from: from});
    Fiber(function () {
        var result = service.process(xmlParam);
        logger.info("view result", result);
        res.send(result);
    }).run();
});


router.get('/mongoTest', function (req, res) {
    Fiber(function () {
        var result = MongBase.findManySync("games", {});
        //if (err)logger.error("mongodb init error", err);
        logger.info("test result", result.length);
        res.send("res send finish~");
        logger.info("res send finish~");
    }).run();
});

module.exports = router;